import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class CreditMenu extends ScreenManager{

	private static final long serialVersionUID = 1L;
	private String userName = "";
	private int dy = 1;
	private JLabel resultLabel;
	
	public CreditMenu(String name){
		userName = name;
		JPanel creditMenu = new JPanel();
		getContentPane().add(creditMenu);
		
		ImageIcon backBg = new ImageIcon(getClass().getResource("bgs/backBg.jpg"));
		
		creditMenu.setLayout(null);
		resultLabel = fillLabel();
		resultLabel.setBounds(90, -350, 200, 350);
		resultLabel.setOpaque(false);
		resultLabel.setFont(new Font("Arial", Font.BOLD, 14));
		creditMenu.add(resultLabel);
		
		creditAnimation();
		
		JButton backButton = new JButton("Back", backBg);
		backButton.addActionListener( new ActionListener()
		{
		    public void actionPerformed(ActionEvent e)
		    {
		    	closeTab();
		    	MainMenu mainMenu = new MainMenu(userName);
		    	mainMenu.setVisible(true);
		    }
		});
		
		backButton.setBounds(300, 250, 95, 55);
		creditMenu.add(backButton);
		
	}
	private JLabel fillLabel(){
		String labelString = "<html>";
		DatabaseManager.openConnection();
		Statement stmt = null;
		try {
			String sql = "Select * from flappybirdv2db.credittable";
			stmt = DatabaseManager.conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			
			while(rs.next()){
				labelString = labelString + "<br>Programmer Name: " + rs.getString("programmer") + "</br><br>School ID:"
				+ rs.getString("schoolID") + ", " + rs.getString("groupNo")  + ".</br>";
				labelString = labelString + "<br></br>";
			}
			DatabaseManager.closeConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		labelString = labelString + "</html>";
		JLabel returnLabel = new JLabel(labelString);
		return returnLabel;
	}
	
	private void closeTab(){
    	this.dispatchEvent(new WindowEvent(this,WindowEvent.WINDOW_CLOSING));
	}
	
	private void creditAnimation(){
		final Timer t = new Timer();
		t.scheduleAtFixedRate(new TimerTask(){
			public void run(){
				if(resultLabel.getY() < 400)
					resultLabel.setBounds(90, resultLabel.getY() + dy, 200, 350);
				else
					resultLabel.setBounds(90, -350, 200, 350);
				
			}

		}, 10, 10);
	}
}
